#!/bin/bash

# Copyright 2018-2020 Arm Limited.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This script is always using a relative path to SRCDIR, so BUILDDIR
# and SRCDIR should be moved together (i.e. BUILDDIR location is not
# independent of SRCDIR).

BASENAME=$(basename $0)
SCRIPT_DIR="$(dirname "${BASH_SOURCE[0]}")"

function usage() {
    cat <<EOF
$BASENAME

Bootstraps an output directory for Bob tests. This script allows
working directory and build output directory to be independently
set.

Usage:
 source_dir/$BASENAME -o path

Options
  -o DIR  Output directory. Defaults to build.
  -h      Help text

The working directory is set to match the current working directory.

The build output directory is set to the directory specified by the -o
option.

The source directory is inferred from the location of $BASENAME, and
cannot be independently changed.

EOF
}

source "${SCRIPT_DIR}/bootstrap_utils.sh"

while getopts "o:h" opt ; do
    case "${opt}" in
        o)
            BUILDDIR="${OPTARG}"
            ;;
        h)
            usage
            exit
            ;;
        [?])
            usage
            exit 1
            ;;
    esac
done
shift $((OPTIND - 1))

# Select a BUILDDIR if not provided one
if [[ -z "$BUILDDIR" ]]; then
    echo "BUILDDIR is not set - using build"
    BUILDDIR=build
fi

# The tests need a symlink in the source directory to the parent bob
# directory, as Blueprint won't accept ..
create_link .. "${SCRIPT_DIR}/bob"

# Bootstrap Bob
export CONFIGNAME="bob.config"
export SRCDIR="${SCRIPT_DIR}"
export BUILDDIR
export BLUEPRINT_LIST_FILE="${SRCDIR}/bplist"

"${SCRIPT_DIR}/bob/bootstrap_linux.bash"

# Pick up some info that bob has worked out
source "${BUILDDIR}/.bob.bootstrap"

# Setup the buildme script to just run bob
ln -sf "bob" "${BUILDDIR}/buildme"

# Print info for users
echo "To configure the build directory, run ${BUILDDIR}/config ARGS"
echo "Then build with ${BUILDDIR}/buildme"
